package com.itzhoun.response;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itzhoun.annotation.Encrypt;
import com.itzhoun.properties.EncryptProperties;
import com.itzhoun.utils.AesUtils;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.annotation.Resource;

/**
 * @author 周楠
 * @Date 2022/11/30/下午 8:07
 */
@EnableConfigurationProperties(EncryptProperties.class)
@ControllerAdvice
public class EncryptResponse implements ResponseBodyAdvice<ResponseData> {

    private ObjectMapper om = new ObjectMapper();

    @Resource
    private EncryptProperties encryptProperties;

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return methodParameter.hasMethodAnnotation(Encrypt.class);
    }

    @Override
    public ResponseData beforeBodyWrite(ResponseData responseData, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        byte[] keyBytes = encryptProperties.getKey().getBytes();
        try {
            if (responseData.getMessage()!=null) {
                responseData.setMessage(AesUtils.encrypt(responseData.getMessage().getBytes(),keyBytes));
            }
            if (responseData.getData() != null) {
                responseData.setData(AesUtils.encrypt(om.writeValueAsBytes(responseData.getData()), keyBytes));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return responseData;
    }
}
